<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			#canvas{
				display: block;
				margin: 20px auto;
				background-color: #000;
				box-shadow: 0 0 10px rgba(0,0,0,0.5);
			}
		</style>
	</head>
	<body>
		<canvas id="canvas"></canvas>
		<script src="../libs/utils.js"></script>
		<script src="../components/ball.js"></script>
		<script type="text/javascript">
			var canvas = document.querySelector('#canvas')
			var ctx = canvas.getContext('2d');
			
			var w = canvas.width = 500;
			var h = canvas.height = 300
			// 创建一个对象池。
			var balls = []
			// 小球个数
			var ballNum = 20
			// 创建小球对象
			createBalls();
			
			(function move(){
				window.requestAnimationFrame(move);
				ctx.clearRect(0,0,w,h)
				ballMove()
			})()
			// 小球移动
			function ballMove(){
				var i = balls.length
				while(i--){
					var ball = balls[i]
					// x,y坐标+=初始速度
					ball.x+=ball.vx
					ball.y+=ball.vy
					ball.render(ctx);
					// 判断边界，移除小球
					if(ball.x - ball.r >=w || ball.x + ball.r<=0 || ball.y -ball.r>=h || ball.y + ball.r<=0){
						if(balls.length===1){
							console.log('小球全部移除了');
						}else{
							console.log('小球:'+ball.id+'被移除了');
						}
						balls.splice(i,1)
					}
				}
			}
			// 创建小球对象
			function createBalls(){
				for(var i =0;i<ballNum;i++){
					balls.push(new Ball({
						x:Math.random()*w,
						y:Math.random()*h,
						r:Math.random()*20+30,
						fillStyle:`rgba(${parseInt(Math.random()*200) +55},${parseInt(Math.random()*200) +55},${parseInt(Math.random()*200) +55},1)`,
						// 初始速度
						vx:3*(Math.random()-0.5) ,
						vy:3*(Math.random()-0.5),
						id:'ball'+i
					}))
				}
				
			}
			
		</script>
	</body>
</html>
